package com.fanbuchi.fukua.net;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.fanbuchi.fukua.application.SuperApp;

import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2015/10/23.
 */
public abstract class BaseUICallBack<T> extends StringsCallBack  {
    UIHandler mHandler = new UIHandler(this);
    T t;
    Class<T> p;
    private BaseUICallBack(){}

    protected BaseUICallBack(Class<T> p){
        this.p=p;
    }

    @Override
    public void onResponseOk(String body) {
        try {
            System.out.println(body);
            t=(T) SuperApp.getMapper().readValue(body,p);
            Message message=Message.obtain();
            message.obj=t;
            mHandler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public abstract void onResponseOk(T body);



    static class UIHandler<T> extends Handler {
        private WeakReference mWeakReference;
        public UIHandler(BaseUICallBack callback){
            super(Looper.getMainLooper());
            mWeakReference=new WeakReference(callback);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseUICallBack<T> uiCallBack=(BaseUICallBack<T>) mWeakReference.get();
            T t = (T) msg.obj;
            if (uiCallBack!=null){
                uiCallBack.onResponseOk(t);
            }
        }
    }

}
